<template>
  <div class="agent-selection">
    <div class="header">
      <h1 class="title">AI角色扮演平台</h1>
      <p class="subtitle">选择一个AI智能体开始语音对话</p>

      <div class="header-actions">
        <el-button @click="showCreateDialog = true" type="success" icon="Plus">
          新增智能体
        </el-button>
        <el-button @click="$router.push('/knowledge')" icon="FolderOpened">
          知识库
        </el-button>
        <el-button type="primary" @click="$router.push('/history')" icon="ChatLineSquare">
          聊天历史
        </el-button>
        <el-button @click="$router.push('/performance')" icon="DataAnalysis" circle title="性能监控" />
        <el-dropdown @command="handleUserCommand">
          <el-button icon="User" circle />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item disabled>{{ userStore.nickname }}</el-dropdown-item>
              <el-dropdown-item command="logout" divided icon="SwitchButton">
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="agents-container">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="error" class="error">
        <el-alert
          title="加载失败"
          :description="error"
          type="error"
          show-icon
          @close="loadAgents"
        />
      </div>

      <div v-else class="agents-grid">
        <div
          v-for="agent in agents"
          :key="agent.id"
          class="agent-card"
        >
          <div class="agent-avatar">
            <el-avatar
              :size="80"
              :src="agent.avatarUrl"
              :alt="agent.name"
            >
              <el-icon size="40"><Avatar /></el-icon>
            </el-avatar>
          </div>

          <div class="agent-info">
            <h3 class="agent-name">{{ agent.name }}</h3>
            <p class="agent-description">{{ agent.description }}</p>
          </div>

          <div class="agent-actions">
            <el-button type="primary" size="large" round @click.stop="selectAgent(agent)">
              <el-icon><Microphone /></el-icon>
              开始对话
            </el-button>
            <div class="agent-edit-actions">
              <el-button
                type="warning"
                size="small"
                circle
                @click.stop="editAgent(agent)"
                title="编辑智能体"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建智能体对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新增智能体"
      width="600px"
      :close-on-click-modal="false"
      @open="handleDialogOpen"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="智能体标识" prop="agentKey">
          <el-input
            v-model="createForm.agentKey"
            placeholder="请输入智能体唯一标识，如：assistant-001"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="智能体名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入智能体名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="智能体描述" prop="description">
          <el-input
            v-model="createForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入智能体描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input
            v-model="createForm.avatarUrl"
            placeholder="请输入头像图片URL（可选）"
          />
        </el-form-item>

        <el-form-item label="系统提示词" prop="systemPrompt">
          <el-input
            v-model="createForm.systemPrompt"
            type="textarea"
            :rows="6"
            placeholder="请输入系统提示词，定义智能体的角色和行为..."
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="默认音色" prop="defaultVoiceType">
          <el-select
            v-model="createForm.defaultVoiceType"
            placeholder="请选择默认音色"
            style="width: 100%"
            filterable
            :loading="voiceLoading"
          >
            <el-option-group
              v-for="category in voiceCategories"
              :key="category"
              :label="category"
            >
              <el-option
                v-for="voice in getVoicesByCategory(category)"
                :key="voice.voice_type"
                :label="voice.voice_name"
                :value="voice.voice_type"
              >
                <div class="voice-option">
                  <span>{{ voice.voice_name }}</span>
                  <el-button
                    type="text"
                    size="small"
                    @click.stop="playVoicePreview(voice)"
                    :loading="playingVoice === voice.voice_type"
                  >
                    <el-icon><VideoPlay /></el-icon>
                  </el-button>
                </div>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number
            v-model="createForm.sortOrder"
            :min="0"
            :max="999"
            placeholder="数值越大排序越靠前"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否支持知识库查询" prop="status">
          <el-radio-group v-model="createForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleCreateAgent"
            :loading="creating"
          >
            创建
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑智能体对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑智能体"
      width="600px"
      :close-on-click-modal="false"
      @open="handleEditDialogOpen"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="智能体标识" prop="agentKey">
          <el-input
            v-model="editForm.agentKey"
            placeholder="请输入智能体唯一标识，如：assistant-001"
            maxlength="50"
            show-word-limit
            disabled
          />
          <div class="form-tip">智能体标识创建后不可修改</div>
        </el-form-item>

        <el-form-item label="智能体名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入智能体名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="智能体描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入智能体描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input
            v-model="editForm.avatarUrl"
            placeholder="请输入头像图片URL（可选）"
          />
        </el-form-item>

        <el-form-item label="系统提示词" prop="systemPrompt">
          <el-input
            v-model="editForm.systemPrompt"
            type="textarea"
            :rows="6"
            placeholder="请输入系统提示词，定义智能体的角色和行为..."
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="默认音色" prop="defaultVoiceType">
          <el-select
            v-model="editForm.defaultVoiceType"
            placeholder="请选择默认音色"
            style="width: 100%"
            filterable
            :loading="voiceLoading"
          >
            <el-option-group
              v-for="category in voiceCategories"
              :key="category"
              :label="category"
            >
              <el-option
                v-for="voice in getVoicesByCategory(category)"
                :key="voice.voice_type"
                :label="voice.voice_name"
                :value="voice.voice_type"
              >
                <div class="voice-option">
                  <span>{{ voice.voice_name }}</span>
                  <el-button
                    type="text"
                    size="small"
                    @click.stop="playVoicePreview(voice)"
                    :loading="playingVoice === voice.voice_type"
                  >
                    <el-icon><VideoPlay /></el-icon>
                  </el-button>
                </div>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number
            v-model="editForm.sortOrder"
            :min="0"
            :max="999"
            placeholder="数值越大排序越靠前"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleUpdateAgent"
            :loading="updating"
          >
            保存修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { agentApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { AiAgent, VoiceInfo, CreateAgentRequest } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const agents = ref<AiAgent[]>([])
const loading = ref(true)
const error = ref('')

// 创建智能体相关数据
const showCreateDialog = ref(false)
const creating = ref(false)
const createFormRef = ref<FormInstance>()
const createForm = ref<CreateAgentRequest>({
  agentKey: '',
  name: '',
  description: '',
  avatarUrl: '',
  systemPrompt: '',
  defaultVoiceType: '',
  status: 1,
  sortOrder: 0
})

// 编辑智能体相关数据
const showEditDialog = ref(false)
const updating = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref<AiAgent>({
  id: 0,
  agentKey: '',
  name: '',
  description: '',
  avatarUrl: '',
  systemPrompt: '',
  defaultVoiceType: '',
  status: 1,
  sortOrder: 0,
  createTime: '',
  updateTime: ''
})
const currentEditingAgent = ref<AiAgent | null>(null)

// 音色相关数据
const voiceList = ref<VoiceInfo[]>([])
const voiceLoading = ref(false)
const playingVoice = ref('')

// 表单验证规则
const createRules: FormRules = {
  agentKey: [
    { required: true, message: '请输入智能体标识', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入智能体描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  systemPrompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 20, max: 2000, message: '长度在 20 到 2000 个字符', trigger: 'blur' }
  ],
  defaultVoiceType: [
    { required: true, message: '请选择默认音色', trigger: 'change' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序权重', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '排序权重必须在 0-999 之间', trigger: 'blur' }
  ]
}

// 编辑表单验证规则（与创建规则类似，但不验证agentKey）
const editRules: FormRules = {
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入智能体描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  systemPrompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 20, max: 2000, message: '长度在 20 到 2000 个字符', trigger: 'blur' }
  ],
  defaultVoiceType: [
    { required: true, message: '请选择默认音色', trigger: 'change' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序权重', trigger: 'blur' },
    { type: 'number', min: 0, max: 999, message: '排序权重必须在 0-999 之间', trigger: 'blur' }
  ]
}

// 计算属性：音色分类
const voiceCategories = computed(() => {
  const categories = [...new Set(voiceList.value.map(voice => voice.category))]
  return categories.sort()
})

// 根据分类获取音色列表
const getVoicesByCategory = (category: string) => {
  return voiceList.value.filter(voice => voice.category === category)
}

// 加载智能体列表
const loadAgents = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await agentApi.getEnabledAgents()
    if (response.code === 200) {
      agents.value = response.data
    } else {
      error.value = response.message || '获取智能体列表失败'
    }
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('加载智能体失败:', err)
  } finally {
    loading.value = false
  }
}

// 选择智能体
const selectAgent = (agent: AiAgent) => {
  ElMessage.success(`已选择 ${agent.name}`)
  router.push(`/chat/${agent.id}`)
}

// 处理用户命令
const handleUserCommand = async (command: string) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm(
        '确定要退出登录吗？',
        '确认退出',
        {
          confirmButtonText: '退出',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )

      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/login')
    } catch (error) {
      // 用户取消
    }
  }
}

// 加载音色列表
const loadVoiceList = async () => {
  try {
    voiceLoading.value = true
    const response = await agentApi.getVoiceList()
    if (response.code === 200) {
      voiceList.value = response.data
    } else {
      ElMessage.error('获取音色列表失败: ' + response.message)
    }
  } catch (err) {
    console.error('加载音色列表失败:', err)
    ElMessage.error('获取音色列表失败，请检查网络连接')
  } finally {
    voiceLoading.value = false
  }
}

// 播放音色预览
const playVoicePreview = async (voice: VoiceInfo) => {
  if (!voice.url) {
    ElMessage.warning('该音色暂无预览音频')
    return
  }

  try {
    playingVoice.value = voice.voice_type
    const audio = new Audio(voice.url)

    audio.onended = () => {
      playingVoice.value = ''
    }

    audio.onerror = () => {
      playingVoice.value = ''
      ElMessage.error('音频播放失败')
    }

    await audio.play()
  } catch (err) {
    playingVoice.value = ''
    ElMessage.error('音频播放失败')
    console.error('播放音色预览失败:', err)
  }
}

// 处理创建智能体
const handleCreateAgent = async () => {
  if (!createFormRef.value) return

  try {
    const valid = await createFormRef.value.validate()
    if (!valid) return

    creating.value = true
    const response = await agentApi.createAgent(createForm.value)

    if (response.code === 200) {
      ElMessage.success('智能体创建成功')
      showCreateDialog.value = false
      resetCreateForm()
      // 重新加载智能体列表
      await loadAgents()
    } else {
      ElMessage.error('创建失败: ' + response.message)
    }
  } catch (err) {
    console.error('创建智能体失败:', err)
    ElMessage.error('创建失败，请检查网络连接')
  } finally {
    creating.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  createForm.value = {
    agentKey: '',
    name: '',
    description: '',
    avatarUrl: '',
    systemPrompt: '',
    defaultVoiceType: '',
    status: 1,
    sortOrder: 0
  }
  createFormRef.value?.resetFields()
}

// 监听对话框显示，加载音色列表
const handleDialogOpen = () => {
  if (voiceList.value.length === 0) {
    loadVoiceList()
  }
}

// 编辑智能体
const editAgent = (agent: AiAgent) => {
  currentEditingAgent.value = agent
  // 复制数据到编辑表单
  editForm.value = {
    ...agent
  }
  showEditDialog.value = true
}

// 监听编辑对话框显示
const handleEditDialogOpen = () => {
  if (voiceList.value.length === 0) {
    loadVoiceList()
  }
}

// 处理更新智能体
const handleUpdateAgent = async () => {
  if (!editFormRef.value || !currentEditingAgent.value) return

  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return

    updating.value = true
    const response = await agentApi.updateAgent(editForm.value)

    if (response.code === 200) {
      ElMessage.success('智能体更新成功')
      showEditDialog.value = false
      // 重新加载智能体列表
      await loadAgents()
    } else {
      ElMessage.error('更新失败: ' + response.message)
    }
  } catch (err) {
    console.error('更新智能体失败:', err)
    ElMessage.error('更新失败，请检查网络连接')
  } finally {
    updating.value = false
  }
}

// 删除智能体
const deleteAgent = async (agent: AiAgent) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除智能体"${agent.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const response = await agentApi.deleteAgent(agent.id)
    if (response.code === 200) {
      ElMessage.success('智能体删除成功')
      // 重新加载智能体列表
      await loadAgents()
    } else {
      ElMessage.error('删除失败: ' + response.message)
    }
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除智能体失败:', err)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadAgents()
})
</script>

<style scoped>
.agent-selection {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 20px;
}

.header {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 40px;
  position: relative;
  background: white;
  padding: 40px 20px;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 40px;
}

.title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 12px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  font-size: 1.1rem;
  color: #6c757d;
  margin: 0 0 20px 0;
  font-weight: 400;
}

.header-actions {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  gap: 8px;
  align-items: center;
}

.agents-container {
  max-width: 1200px;
  margin: 0 auto;
}

.loading, .error {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f1f3f4;
}

.agents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 24px;
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.agent-card {
  background: white;
  border-radius: 20px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  text-align: center;
  border: 1px solid #f1f3f4;
  position: relative;
  overflow: hidden;
}

.agent-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s;
}

.agent-card:hover::before {
  left: 100%;
}

.agent-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  border-color: #e3f2fd;
}

.agent-avatar {
  margin-bottom: 20px;
}

.agent-info {
  margin-bottom: 24px;
}

.agent-name {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 12px 0;
}

.agent-description {
  color: #7f8c8d;
  line-height: 1.6;
  margin: 0;
}

.agent-actions .el-button {
  width: 100%;
  height: 50px;
  font-size: 1.1rem;
  font-weight: 600;
  border-radius: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

.agent-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 智能体编辑操作按钮 */
.agent-edit-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  justify-content: center;
}

.agent-edit-actions .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
}

/* 音色选项样式 */
.voice-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.voice-option span {
  flex: 1;
}

.voice-option .el-button {
  margin-left: 8px;
  padding: 0;
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

/* 对话框样式优化 */
.el-dialog__body {
  padding: 20px 20px 0 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
